package com.syf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.syf.domain.store.BsSoftwareRelease;
import com.syf.service.BsSoftwareReleaseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syf.domain.store.BsEvaluation;
import com.syf.mapper.BsEvaluationMapper;
import com.syf.service.BsEvaluationService;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.OptionalDouble;
import java.util.stream.Collectors;

/**
*
*
*@author syf
*@create 2022-02-07 19:09
*/
@Slf4j
@Service
public class BsEvaluationServiceImpl extends ServiceImpl<BsEvaluationMapper, BsEvaluation> implements BsEvaluationService{

    @Autowired
    private BsSoftwareReleaseService bsSoftwareReleaseService;


    /**
     * 用户发表一个评论
     * @param bsEvaluation
     * @return
     */
    @Override
    @Transactional
    public boolean addEvaluation(BsEvaluation bsEvaluation) {
        boolean save = save(bsEvaluation);
        if(save){
            LambdaQueryWrapper<BsEvaluation> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(BsEvaluation::getSoftwareCode,bsEvaluation.getSoftwareCode())
                    .select(BsEvaluation::getRate);
            List<BsEvaluation> list = list(wrapper);

            Double rate = list.stream().mapToDouble(evaluation ->{
                return Double.parseDouble(evaluation.getRate());
            }).average().getAsDouble();

            BigDecimal avgRate = new BigDecimal(rate).setScale(1, RoundingMode.HALF_UP);
            log.info("平均评分：{}", avgRate+"");
            BsSoftwareRelease bsSoftwareRelease = bsSoftwareReleaseService.selBycode(bsEvaluation.getSoftwareCode());
            bsSoftwareRelease.setAvgScore(avgRate+"");
            boolean update = bsSoftwareReleaseService.updateById(bsSoftwareRelease);
            return update;
        }
        return save;
    }

    /**
     * 分页条件查询--用户评价列表
     * @return
     */
    @Override
    public Page<BsEvaluation> findByPage(BsEvaluation bsEvaluation) {
        String softwareCode = bsEvaluation.getSoftwareCode();
        Page<BsEvaluation> page = new Page<BsEvaluation>(bsEvaluation.getCurrent(),bsEvaluation.getSize());
        LambdaQueryWrapper<BsEvaluation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(softwareCode),BsEvaluation::getSoftwareCode,softwareCode)
                .orderByDesc(BsEvaluation::getCreateTime);
        Page<BsEvaluation> evaluationPage = page(page, wrapper);
        return evaluationPage;
    }
}
